package aaa.schedule;

import java.util.Iterator;


public class Lessons implements Iterable<Lesson> {
	
	private Lesson[] lessons ;
	private int nLessons ;
	
	public Lessons () {
		this.lessons = new Lesson[0] ;
		this.nLessons = 0 ;
	}// Lessons()
	
	/**
	 * Ensures taht the array is big enough to accommodate the given number of elements.
	 * If the array is too small, a new one is created and padded with null at the end.
	 * 
	 * @param 	size
	 */
	public void ensureCapacity (int size) {
		if (size > this.lessons.length) {
			Lesson[] tmp = new Lesson[size] ;
			for(int l = 0; l < this.lessons.length; l++) {
				tmp[l] = this.lessons[l] ;
			}// for
			for(int l = this.lessons.length; l < tmp.length; l++) {
				tmp[l] = null ;
			}// for
			this.lessons = tmp ;
		}// if
	}// ensureCapacity()
	
	/**
	 * Insert a new Lesson using the "insertion sort" algorithm.
	 * 
	 * @param 	l
	 * 			Lesson to add
	 */
	public void insert (Lesson l) {
		int pos = this.nLessons ;
		while ((pos > 0) && (this.lessons[pos-1].compareTo(l) > 0)) {
			this.lessons[pos] = this.lessons[pos-1] ;
			--pos ;
		}// while
		this.lessons[pos] = l ;
		this.nLessons++ ;
	}// insert(Lesson)
	
	/**
	 * Appends a new Lesson.
	 * 
	 * @param 	l
	 * 			Lesson to append
	 */
	public void append (Lesson l) {
		this.lessons[this.nLessons] = l ;
		this.nLessons++ ;
	}// append(Lesson)
	
	/**
	 * 
	 */
	public int size () {
		return this.nLessons ;
	}// size()

	public Lesson get(int i) {
		return this.lessons[i] ;
	}// get(int)

	public Iterator<Lesson> iterator() {
		return new LessonIterator(this) ;
	}
	
	class LessonIterator implements Iterator<Lesson> {

		protected int next ;
		protected Lessons lessons ;
		
		public LessonIterator(Lessons lessons) {
			this.next = 0 ;
			this.lessons = lessons ;
		}
		
		public boolean hasNext() {
			return (this.next < this.lessons.size()) ;
		}

		public Lesson next() {
			int next = this.next ;
			this.next++ ;
			return this.lessons.get(next) ;
		}

		public void remove() {
			throw new UnsupportedOperationException("LessonIterator.remove n'a pas été implanté.") ;
		}
		
	}

}// Class Lessons